package com.dp.mallchat.common.common.event.listener;

import com.dp.mallchat.common.chat.dao.MessageDao;
import com.dp.mallchat.common.chat.dao.MessageMarkDao;
import com.dp.mallchat.common.chat.domain.entity.Message;
import com.dp.mallchat.common.chat.domain.enums.MessageMarkTypeEnum;
import com.dp.mallchat.common.chat.domain.enums.MessageTypeEnum;
import com.dp.mallchat.common.common.domain.dto.MsgMarkEventDto;
import com.dp.mallchat.common.common.event.MsgMarkEvent;
import com.dp.mallchat.common.user.domain.user.enums.IdempotenceEnum;
import com.dp.mallchat.common.user.domain.user.enums.ItemEnum;
import com.dp.mallchat.common.user.domain.ws.resp.WSBaseResp;
import com.dp.mallchat.common.user.service.UserBackpackService;
import com.dp.mallchat.common.user.service.WebSocketService;
import com.dp.mallchat.common.user.service.adapter.WSAdapter;
import com.dp.mallchat.common.user.service.impl.PushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Author: dupeng
 * @CreateTime: 2024-07-31  20:22
 * @Description: 消息表时间监听
 */
@Component
public class MsgMarkEventListener {

    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageMarkDao messageMarkDao;
    @Autowired
    private PushService pushService;
    @Autowired
    private UserBackpackService userBackpackService;


    //文本消息点踩推送事件
    @Async
    @EventListener(classes = MsgMarkEvent.class)
    public void wsUserMarkEvent(MsgMarkEvent msgMarkEvent) {
        MsgMarkEventDto dto = msgMarkEvent.getMsgMarkEventDto();
        Integer msgMarkCount = messageMarkDao.getMsgMarkCount(dto.getMsgId(), dto.getMarkType());
        pushService.sendPushMsg(WSAdapter.buildMsgMark(dto, msgMarkCount));

    }

    //文本消息点赞发送徽章事件
    @Async
    @EventListener(classes = MsgMarkEvent.class)
    public void wsUserMarkLikeEvent(MsgMarkEvent msgMarkEvent) {
        MsgMarkEventDto dto = msgMarkEvent.getMsgMarkEventDto();
        //仅对文本消息有效
        Message message = messageDao.getById(dto.getMsgId());
        if (!Objects.equals(MessageTypeEnum.TEXT.getType(), message.getType())) {
            return;
        }

        //消息被标记次数
        Integer msgMarkCount = messageMarkDao.getMsgMarkCount(dto.getMsgId(), dto.getMarkType());
        if (msgMarkCount >= 10) {
            return;
        }
        //尝试给用户发送一张徽章 点赞
        if (MessageMarkTypeEnum.LIKE.getType().equals(dto.getMarkType())) {
            userBackpackService.acquireItem(message.getFromUid(), ItemEnum.LIKE_BADGE.getId(), IdempotenceEnum.MSG_ID, dto.getUid().toString());
        }
    }

}
